package com.bing.test;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQTopic;
import org.junit.Before;
import org.junit.Test;

import javax.jms.*;

/**
 * Created by Administrator on 2015/5/10.
 */
public class HelloTopic {
    private ActiveMQConnectionFactory activeMQConnectionFactory;

    Session session;
    Connection connection;

    @Before
    public void beforeClass() throws JMSException {
        activeMQConnectionFactory = new ActiveMQConnectionFactory("vm://localhost");
        connection = activeMQConnectionFactory.createConnection();
        connection.start();
    }

    @Test
    public void testTopic() throws JMSException {
        System.out.println("Start test topic");
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = new ActiveMQTopic("hello/topic");

        MessageConsumer consumer1 = session.createConsumer(topic);
        consumer1.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                try {
                    System.out.println("consumer1 接收消息:" + ((TextMessage) message).getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });

        MessageConsumer consumer2 = session.createConsumer(topic);
        consumer2.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                try {
                    System.out.println("consumer2 接收消息:" + ((TextMessage) message).getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });

        MessageProducer messageProducer = session.createProducer(topic);
        for (int i = 0; i <= 20; i++) {
            messageProducer.send(session.createTextMessage("topic" + i));
        }
    }

}
